package response

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"strings"
)

// JsonRes 数据返回通用JSON数据结构
type JsonRes struct {
	Code int         `json:"code"` // 错误码((0:成功, 1:失败, >1:错误码))
	Msg  string      `json:"msg"`  // 提示信息
	Data interface{} `json:"data"` // 返回数据(业务接口定义具体数据结构)
}

type TableJsonRes struct {
	JsonRes
	Count uint `json:"count"` // 记录总数
}

// Json 返回标准JSON数据。
func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
	var responseData interface{}
	if len(data) > 0 {
		responseData = data[0]
	} else {
		responseData = g.Map{}
	}
	r.Response.WriteJson(JsonRes{
		Code: code,
		Msg:  message,
		Data: responseData,
	})
}

func TableJson(r *ghttp.Request, code int, count uint, data ...interface{}) {
	var responseData interface{}
	if len(data) > 0 {
		responseData = data[0]
	} else {
		responseData = g.Map{}
	}

	var Json TableJsonRes
	Json.Code = code
	Json.Msg = "success"
	Json.Data = responseData
	Json.Count = count

	r.Response.WriteJson(Json)
}

// JsonExit 返回标准JSON数据并退出当前HTTP执行函数。
func JsonExit(r *ghttp.Request, code int, message string, data ...interface{}) {
	var _Data map[string]interface{}
	if len(data) > 0 {
		_Data = gconv.Map(data[0])
	} else {
		_Data = map[string]interface{}{}
	}
	if value, ok := _Data["count"]; ok {
		TableJson(r, code, gconv.Uint(value), _Data["data"])
	} else {
		Json(r, code, message, data...)
	}
	r.Exit()
}

func dataReturn(r *ghttp.Request, code int, req ...interface{}) *JsonRes {
	var msg string
	var data interface{}
	if len(req) > 0 {
		msg = gconv.String(req[0])
	}
	if len(req) > 1 {
		data = req[1]
	}
	response := &JsonRes{
		//ID:      r.GetCtxVar("RequestId").String(),
		Code: code,
		Msg:  msg,
		Data: data,
	}
	r.SetParam("apiReturnRes", response)
	return response
}

// WantsJson 判断是否是Json请求
func WantsJson(r *ghttp.Request) bool {
	return strings.Contains(r.Header.Get("Accept"), "application/json")
}

// IsRestfulRequest 是否是接口请求
func IsRestfulRequest(r *ghttp.Request) bool {
	return r.IsAjaxRequest() || WantsJson(r)
}

// AuthFail 认证失败
func AuthFail(r *ghttp.Request) {
	res := dataReturn(r, 401, "请先授权登录！")
	r.Response.WriteJsonExit(res)
}

func Error(r *ghttp.Request) {
	r.Response.ClearBuffer()
	res := dataReturn(r, 500, "服务器居然开小差了，请稍后再试吧！")
	r.Response.WriteJsonExit(res)
}
